package org.example;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.*;
import java.awt.*;
import javax.imageio.ImageIO;

public class Main {
    public static void main(String[] args) {
        String inputPngPath = "D:\\Documents\\workspaces\\Gitee\\java-projects\\untitled\\src\\main\\resources\\ame\\Snipaste.png"; // 输入PNG文件路径
        String outputFilePath = "output.png"; // 输出文件路径

        try (FileInputStream fis = new FileInputStream(inputPngPath);
             FileOutputStream fos = new FileOutputStream(outputFilePath)) {

            // 步骤1: 读取PNG图片
            // 读取图片到内存（这里为了示例简单起见，直接读取整个文件到字节数组）
            byte[] imageBytes = new byte[(int) new File(inputPngPath).length()];
            fis.read(imageBytes);

            // 步骤2: 图片处理
            // 将字节数组转换为图像对象
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));

            // 这里可以添加图片处理逻辑，例如转换为灰度图
            BufferedImage processedImage = processImage(image);

            // 步骤3: 保存图片数据
            // 将处理后的图像转换为字节数组
            byte[] outputBytes = convertImageToBytes(processedImage);

            // 写入到输出文件
            fos.write(outputBytes);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 图片处理示例方法：将图片转换为灰度图
    private static BufferedImage processImage(BufferedImage original) {
        BufferedImage grayImage = new BufferedImage(
                original.getWidth(), original.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D g = grayImage.createGraphics();
        // 绘制原始图片到灰度图片上
        g.drawImage(original, 0, 0, null);
        g.dispose();
        return grayImage;
    }

    // 将图像转换为字节数组的方法
    private static byte[] convertImageToBytes(BufferedImage image) throws IOException {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "png", bos);
            return bos.toByteArray();
        }
    }
}
